#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 The SymbiFlow Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC

import os
import sys
import glob

templ = """/*
:name: rsd
:description: Full RSD core test
:files: {0}
:incdirs: {1}
:tags: rsd
:top_module: Core
:timeout: 100
*/
"""

try:
    third_party_dir = os.environ['THIRD_PARTY_DIR']
    tests_dir = os.environ['TESTS_DIR']
    conf_dir = os.environ['CONF_DIR']
except KeyError:
    print("Export the THIRD_PARTY_DIR, TESTS_DIR and CONF_DIR variables first")
    sys.exit(1)

try:
    tests_subdir = sys.argv[1]
except IndexError:
    print("Usage: ./generator <subdir>")
    sys.exit(1)

rsd_path = os.path.abspath(
    os.path.join(
        third_party_dir, "cores", "rsd", "Processor", "Project",
        "DesignCompiler"))
rsd_tcl = os.path.join(rsd_path, "compile.tcl")

test_dir = os.path.join(tests_dir, 'generated', tests_subdir)

if not os.path.isdir(test_dir):
    os.makedirs(test_dir, exist_ok=True)

test_file = os.path.join(test_dir, "rsd.sv")

sources = os.path.abspath(test_file) + ' '
incdirs = os.path.join(rsd_path, "../../Src") + ' '

with open(rsd_tcl, "r") as f:
    for line in f.readlines():
        line = line.strip()
        if line.startswith("../../Src"):
            sources += os.path.join(rsd_path, line) + ' '

# The compile.tcl file is missing some required sources for whatever reason.
sources += os.path.join(rsd_path, "../../Src/Cache/CacheFlushManager.sv") + ' '
sources += os.path.join(
    rsd_path, "../../Src/Cache/CacheFlushManagerIF.sv") + ' '

with open(test_file, "w") as f:
    f.write(templ.format(sources, incdirs))
    f.write("`define RSD_SYNTHESIS\n")
    f.write("`define RSD_SYNTHESIS_DESIGN_COMPILER\n")
